package com.atgugu.flink.chapter11;

import com.atgugu.flink.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Author lzc
 * @Date 2022/4/11 9:12
 */
public class Flink14_Time_Event {
    public static void main(String[] args) {
        // 流->动态表->连续查询->动态表->流
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        SingleOutputStreamOperator<WaterSensor> stream = env
            .fromElements(
                new WaterSensor("sensor_1", 1001L, 1),
                new WaterSensor("sensor_2", 2000L, 2),
                new WaterSensor("sensor_1", 3000L, 3),
                new WaterSensor("sensor_1", 4000L, 4),
                new WaterSensor("sensor_2", 5000L, 5),
                new WaterSensor("sensor_1", 6000L, 6)
            )
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((ws, ts) -> ws.getTs())
            );
        
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        // 添加一个新的字段作为事件时间
//        Table table = tEnv.fromDataStream(stream, $("id"),$("ts"), $("vc"), $("et").rowtime()); // 添加一列: 时间列
        
        // 把现有的列转成事件时间
        Table table = tEnv.fromDataStream(stream, $("id"),$("ts").rowtime(), $("vc"));
        table.printSchema();
        table.execute().print();
        
        
    }
}
